package com.atguigu.gulimall.member.service.impl;

import com.atguigu.gulimall.member.dao.MemberLevelDao;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.entity.SocialUser;
import com.atguigu.gulimall.member.exception.PhoneExistException;
import com.atguigu.gulimall.member.exception.UsernameExistException;
import com.atguigu.gulimall.member.vo.MemberLoginVo;
import com.atguigu.gulimall.member.vo.MemberRegistVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vo) {
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = new MemberEntity();

        //设置默认等级
        MemberLevelEntity memberLevelEntity = memberLevelDao.getDefaultLevel();

        memberEntity.setLevelId(memberLevelEntity.getId());
        //检查用户名和手机号是否唯一,为了让controller感知到异常，采用异常机制

        checkPhoneUnique(vo.getPhone());

        checkUsernameUnique(vo.getUserName());

        memberEntity.setMobile(vo.getPhone());
        memberEntity.setUsername(vo.getUserName());

        //密码要加密存储
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        memberEntity.setPassword(encoder.encode(vo.getPassword()));



        memberDao.insert(memberEntity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException{
        MemberDao memberDao = this.baseMapper;

        Integer count = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));

        if(count>0){

            throw new PhoneExistException();
        }

    }

    @Override
    public void checkUsernameUnique(String username) throws UsernameExistException{

        MemberDao memberDao = this.baseMapper;

        Integer count = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));

        if(count>0){

            throw new UsernameExistException();
        }

    }

    @Override
    public MemberEntity login(MemberLoginVo memberLoginVo) {

        MemberDao memberDao = this.baseMapper;

        String loginact = memberLoginVo.getLoginact();
        String password = memberLoginVo.getPassword();


        MemberEntity member = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("username", memberLoginVo.getLoginact()).or().eq("mobile", loginact));

        if(member==null){

            return null;
        }else {

            //获取数据库字段
            String passworddb = member.getPassword();
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            System.out.println("password:" + password +",passwordDb" + passworddb );
            boolean matches = encoder.matches(password, passworddb);
            if(matches){
                return member;
            }else {

                return null;
            }


        }


    }

    @Override
    public MemberEntity oauthLogin(SocialUser socialUser) {

        //判断当前社交账号是否已经注册过


        MemberDao memberDao = this.baseMapper;

        MemberEntity member = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", socialUser.getId()));

        if(member!=null){

            //这个用户已经注册
            MemberEntity update = new MemberEntity();

            update.setId(member.getId());
            update.setAccessToken(socialUser.getAccess_token());

            update.setExpiresIn(socialUser.getExpires_in());

            memberDao.updateById(update);

            member.setAccessToken(socialUser.getAccess_token());
            member.setExpiresIn(socialUser.getExpires_in());

            System.out.println("用户已经注册，更新access_token");
            return member;

        }else{

            //没有查到社交用户注册记录，需要注册一个

            MemberEntity regist = new MemberEntity();

            regist.setSocialUid(String.valueOf(socialUser.getId()));
            regist.setNickname(socialUser.getName());
            regist.setAccessToken(socialUser.getAccess_token());
            regist.setExpiresIn(socialUser.getExpires_in());

            memberDao.insert(regist);

            System.out.println("用户未注册，先注册，再返回登录信息");

            return regist;
        }

    }

}